package tenorclient;

import TransportLayer.IDataTransportable;
import TransportLayer.SocketClient;
import TransportLayer.SrtpException;
import cryptography.BasicKeyGenerator;
import cryptography.BasicSaltGenerator;
import java.awt.Component;
import java.awt.Dimension;
import java.util.Collection;
import java.util.Iterator;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import srtp.SceneSrtp;

/**
 *
 * @author Tomasz Nowak
 */
public class Conversation extends Component implements Runnable
{
	private IContact contact;
	private JPanel panel;
	private javax.swing.JTextArea messagesTextArea;
	private IDataTransportable transportEndpoint;
	private JScrollPane scrollingPane;

	private void configurePanel()
	{
		panel = new JPanel();
		messagesTextArea = new javax.swing.JTextArea();
		messagesTextArea.setAutoscrolls(true);
		messagesTextArea.setLineWrap(true);
		messagesTextArea.setEditable(false);
		scrollingPane = new JScrollPane(messagesTextArea);
		scrollingPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		scrollingPane.setPreferredSize(new Dimension(400, 365));
		panel.add(scrollingPane);
	}

	public Conversation( IContact contact_ ) throws SrtpException
	{
		contact = contact_;
		transportEndpoint = new SocketClient(contact.getAddress(), contact.getPort(),
																				 new SceneSrtp(new BasicSaltGenerator(), new BasicKeyGenerator()));
		configurePanel();
	}

	public Conversation( IDataTransportable transportEndpoint_ )
	{
		transportEndpoint = transportEndpoint_;
		configurePanel();
		//todo: use SIP/notary services to identify user
		contact = new Contact(transportEndpoint_.getRemoteEndpointAddress(), transportEndpoint_.getRemoteEndpointPort(),
													"unknown user");
	}

	public IContact getContact()
	{
		return contact;
	}

	public javax.swing.JTextArea getMessageTextField()
	{
		return messagesTextArea;
	}

	public IDataTransportable getTransportEndpoint()
	{
		return transportEndpoint;
	}

	public JPanel getPanel()
	{
		return panel;
	}

	@Override
	public void run()
	{
		while ( true )
		{
			byte[] message = transportEndpoint.receiveMessage();
			updateConversation(contact, new String(message));
		}
	}

	public void updateConversation( IContact user, byte[] message )
	{
		messagesTextArea.setText(messagesTextArea.getText().concat("\n" + user.getName() + ": " + message));
	}

	public void updateConversation( IContact user, String message )
	{
		messagesTextArea.setText(messagesTextArea.getText().concat("\n" + user.getName() + ": " + message));
	}
}
